<template>
  <div class="page-content">
    <div class="header" style="margin-bottom: 1.5rem">
      <h3>题库分组</h3>
    </div>
    <el-row style="margin-top: 1.5rem; width: 100%">
      <!-- <el-col :xs="24" :sm="12" :lg="6">
        <el-input placeholder="部门名称"></el-input>
      </el-col> -->
      <div style="width: 12px"></div>
      <!-- 顶部搜索栏 -->
      <div style="width: 100%">
        <table-bar :showTop="true" @search="search" @reset="resetForm(searchFormRef)" @changeColumn="changeColumn"
          :columns="columns">
          <template #top>
            <el-form :model="searchForm" ref="searchFormRef" label-width="82px">
              <el-row :gutter="20">
                <form-input label="关键字" prop="name" v-model="searchForm.name" />
                <form-select label="车型选择" prop="phone" v-model="searchForm.cardtype" :options="cardtype" />
                <form-select label="分类选择" prop="type_one" v-model="searchForm.conttype_one"
                  :options="typeOptions_two" />
              </el-row>
              <el-row :gutter="20">
                <!-- 创建日期筛选 -->
                <div class="databox" style="margin-bottom: 1.5rem">
                  <label class="el-form-item__label" style="margin-left: 1.5rem">操作时间：</label>
                  <el-date-picker label="操作时间：" v-model="datavalue1" type="datetimerange" start-placeholder="开始日期"
                    end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd"
                    time-format="A hh:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                </div>
                <!-- end创建日期筛选 -->
              </el-row>
            </el-form>
          </template>
        </table-bar>
        <el-col :xs="24" :sm="12" :lg="20">
          <el-button v-ripple>刷新</el-button>
          <el-button @click="showDialog('add')" v-ripple>新增分组</el-button>
        </el-col>
      </div>
      <!-- end顶部搜索栏 -->

      <div> </div>
    </el-row>

    <art-table :data="tableData" :currentPage="pageNum" :pageSize="pageSize" :total="pagetotal"
      @current-change="currentchange" @size-change="sizechange">
      <template #default>
        <el-table-column prop="id" label="ID" width="100" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="name" label="分组名称">
          <template #default="scope">
            {{ formatMenuTitle(scope.row.name) }}
          </template>
        </el-table-column>

        <el-table-column prop="meta.authList" label="图标">
          <el-image class="tableimg"
            src="https://image.lutongjiakao.com/system/bd80f72c469a40a0affb8eb9f9107b22.png"></el-image>
        </el-table-column>

        <el-table-column label="题目数量" prop="id" />

        <el-table-column label="编辑时间" prop="date"> 2022-3-12 12:00:00 </el-table-column>

        <el-table-column fixed="right" label="操作" width="250">
          <template #default="scope">
            <el-button type="warning" size="default" plain>选题</el-button>
            <el-button @click="showDialog('edit', scope.row)" type="primary" size="default" plain>编辑</el-button>
            <el-button @click="handleDelete(scope.row.id)" type="danger" size="default" plain>删除</el-button>
          </template>
        </el-table-column>
      </template>
    </art-table>

    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增分组' : '编辑分组'" width="30%"
      :close-on-click-modal="false">
      <el-form ref="formRef" :rules="rules" :model="form" label-width="120px">
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" :rows="3" />
        </el-form-item>
        <el-form-item label="车型" prop="card_type">
          <el-checkbox-group v-model="checked1" @change="carTypeChange">
            <el-checkbox label="大车" value="1" size="large" />
            <el-checkbox label="小车" value="2" size="large" />
            <el-checkbox label="客车" value="3" size="large" />
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="题目分类" prop="types_one">
          <!-- 复选分类1 分类2 -->
          <el-radio v-model="radio" label="1">科目一</el-radio>
          <el-radio v-model="radio" label="2">科目二</el-radio>
          <el-radio v-model="radio" label="3">科目三</el-radio>
          <el-radio v-model="radio" label="4">科目四</el-radio>
        </el-form-item>
        <el-form-item label="父ID" prop="idsoptionsId">
          <el-cascader v-model="form.parentId" :options="idsoptions"
            :props="{ checkStrictly: true, label: 'name', value: 'id' }" clearable></el-cascader>
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="图标" prop="imageurl">
          <el-upload class="avatar-uploader" style="
              border: 1px dashed var(--el-border-color-darker);
              border-radius: 6px;
              overflow: hidden;
              width: 100%;
              height: 100%;
              display: flex;
              justify-content: center;
              align-items: center;
            " :action="server" :headers="imgheaders" :show-file-list="false" :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <el-image v-if="form.img" :src="form.img" class="avatar" fit="contain"></el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
                <Plus />
              </el-icon></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介" prop="des">
          <el-input v-model="form.des" type="textarea" :rows="6" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit(formRef)">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ButtonMoreItem } from '@/components/core/forms/ArtButtonMore.vue'
import { useMenuStore } from '@/store/modules/menu'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { formatMenuTitle } from '@/router/utils/utils'
import type { UploadFile } from 'element-plus'
import { getcategoryList, operationCategory } from '@/api/questionbanklabel'
import { useUserStore } from '@/store/modules/user'

const userStore = useUserStore()
let { accessToken } = userStore

let server = `${import.meta.env.VITE_API_URL}files`
const imgheaders = { Authorization: 'Bearer ' + accessToken }

const radio = ref('1')
const checked1 = ref([])

const dialogVisible = ref(false)
const permissionDialog = ref(false)
const menuList = computed(() => useMenuStore().getMenuList)

// 新增表单验证规则
const rules = reactive<FormRules>({
  name: [{ required: true, message: '分组名称必须填写', trigger: 'blur' }],
  card_type: [
    {
      asyncValidator: (rule, value, callback) => {
        nextTick(() => {
          if (form.carTypeIds) {
            callback()
          } else {
            callback(new Error('题目分类必须填写111'))
          }
        })
      }
    }
  ]
})

const formRef = ref<FormInstance>()
const dialogImageUrl = ref('')
const disabled_banner = ref(false)
const pagetotal = ref()
const pageNum = ref(1)
const pageSize = ref(10)
const idsoptions = ref()

const form = reactive({
  parentId: [],
  id: '',
  name: '',
  des: '',
  sort: '1',
  status: true,
  imageurl: '',
  types_one: '',
  idsoptionsId: '', // 父id
  carTypeIds: '', // 车型
  img: '' // 上传图片链接
})
const tableData = ref([])
console.log(tableData)

const dialogType = ref('add')

const showDialog = async (type: string, row?: any) => {
  dialogVisible.value = true
  dialogType.value = type

  const parentList = await getParentTreeList()
  idsoptions.value = parentList
  console.log(row, '++??row')
  if (type === 'edit' && row) {
    form.id = row.id
    form.name = row.name
    form.des = row.des
    checked1.value = row.carIds ? row.carIds.split(',') : []
    form.status = row.status
    radio.value = row.categoryIds
    form.parentId = row.parentId ? row.parentId.split(',') : []
    form.des = row.remark
    form.img = row.img
    // form.carTypeIds = row
    form.carTypeIds = row.categoryIds
  } else {
    form.status = row.status === 1
    form.id = ''
    form.name = ''
    form.des = ''
    form.status = true
  }
}

const buttonMoreClick = (item: ButtonMoreItem, row: any) => {
  if (item.key === 'permission') {
    showPermissionDialog()
  } else if (item.key === 'edit') {
    showDialog('edit', row)
  } else if (item.key === 'delete') {
    deleteRole()
  }
}

// 获取树形结构的列表,用于选择父级id
const getParentTreeList = () => {
  return new Promise(async (resolve, reject) => {
    let params = {}
    const res = await getcategoryList.getcategoryTreeList(params)
    if (res.code == 0) {
      resolve(res.data)
    } else {
      reject()
    }
  })
}

// 车型改变处理
const carTypeChange = (item: any) => {
  form.carTypeIds = item.join(',')
}

const showPermissionDialog = () => {
  permissionDialog.value = true
}

const defaultProps = {
  children: 'children',
  label: (data: any) => formatMenuTitle(data.meta?.title) || ''
}

const deleteRole = () => {
  ElMessageBox.confirm('确定删除该分组吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(() => {
    ElMessage.success('删除成功')
  })
}

// 新增 or 修改
const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate(async (valid) => {
    if (!valid) {
      return
    }
    const tempParams: any = {
      name: form.name,
      parentId: form.parentId[form.parentId.length - 1], // 父id
      categoryIds: radio.value, // 分类id
      sort: form.sort,
      carIds: checked1.value.join(','), // 车型
      remark: form.des,
      status: 1,
      img: form.img
    }

    if (form.id) {
      tempParams.id = form.id
    }
    // return
    try {
      if (dialogType.value === 'add') {
        const res = await operationCategory.addCategory(tempParams)
        if (res.code == 0) {
          const message = dialogType.value === 'add' ? '新增成功' : '修改成功'
          ElMessage.success(message)
          dialogVisible.value = false
          formEl.resetFields()
        }
      } else {
        const res = await operationCategory.eidtCategory(tempParams, tempParams.id)
        if (res.code == 0) {
          const message = dialogType.value === 'add' ? '新增成功' : '修改成功'
          ElMessage.success(message)
          dialogVisible.value = false
          formEl.resetFields()
        }
      }
      getquestionbanklabellist()
    } catch (error) {
      ElMessage.error('报错拉')
    }
  })
}

// 删除
const handleDelete = (ids: string) => {
  ElMessageBox.confirm('确定删除该分组吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  })
    .then(async () => {
      const res = await operationCategory.deleteCategory(ids)
      if (res.code == 0) {
        const message = '删除成功!'
        ElMessage.success(message)
        getquestionbanklabellist()
      } else {
        ElMessage.error('删除失败!')
      }
    })
    .catch(() => {
      ElMessage.error('操作已取消!')
    })
  return
}

const formatDate = (date: string) => {
  return new Date(date)
    .toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
    .replace(/\//g, '-')
}

// 上传之前的处理
const beforeAvatarUpload = (file: any) => {
  const isLt2M = file.size / 10240 / 10240 < 2
  if (file.type != 'image/jpeg' && file.type != 'image/png' && file.type != 'image/gif') {
    ElMessage.error('图片类型仅支持JPG/PNG/GIF格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 20MB!!')
    return false
  }
}

// 上传成功
const handleAvatarSuccess = (file: any) => {
  console.log(file)
  form.img = file.data.url
}

//搜索刷新等
const search = () => {
  getquestionbanklabellist()
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
const searchFormRef = ref<FormInstance>()
const columns = reactive([
  { name: '用户信息', show: true },
  { name: '手机号', show: true },
  { name: '性别', show: true },
  { name: '来源', show: true },
  { name: '状态', show: true },
  { name: '创建日期', show: true }
])
const changeColumn = (list: any) => {
  columns.values = list
}
const searchForm = reactive({
  name: '',
  phone: '',
  id: '',
  account: '',
  level: '',
  cardtype: '',
  conttype_one: '',
  conttype_two: ''
})
const cardtype = [
  {
    value: '大车',
    label: '大车'
  },
  {
    value: '小车',
    label: '小车'
  }
]
const typeOptions_two = [
  {
    value: '精选100道',
    label: '精选100道'
  },
  {
    value: '冲刺100道',
    label: '冲刺100道'
  }
]
const datavalue1 = ref('') //操作时间：

//上传图片
const handlePictureCardPreview_banner = (file: UploadFile) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}
//隐藏图片
const handleDownload_banner = (file: UploadFile) => {
  console.log(file)
}
//轮播图部分上传
const handleRemove_banner = (file: UploadFile) => {
  console.log(file)
}
onMounted(() => {
  getquestionbanklabellist() //请求驾校列表接口
})
const getquestionbanklabellist = async () => {
  const obj: any = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    name: searchForm.name, // 分组名称
    startCreateTime: null, // 开始时间
    endCreateTime: null // 结束时间
    // is_display:0
    // type:1
  }
  if (datavalue1.value.length) {
    obj.startCreateTime = datavalue1.value[0]
    obj.endCreateTime = datavalue1.value[1]
  }
  console.log(searchForm, datavalue1, '++??date')
  const res = await getcategoryList.getcategoryId(obj)
  if (res.code == 0) {
    tableData.value = res.data.list
    pagetotal.value = res.data.total
  }
}
//分页数据处理
const currentchange = (val: number) => {
  pageNum.value = val
  getquestionbanklabellist() //请求用户列表接口
}
const sizechange = (val: number) => {
  pageSize.value = val
  pageNum.value = 1
  getquestionbanklabellist() //请求用户列表接口
}
</script>

<style lang="scss" scoped>
.page-content {
  .svg-icon {
    width: 1.8em;
    height: 1.8em;
    overflow: hidden;
    vertical-align: -8px;
    fill: currentcolor;
  }
}

.tag-item+.tag-item {
  margin-left: 5px;
}

.label {
  float: left;
  margin: 0.5rem 0 0.5rem 1.5rem;
  display: inline;
}

.labellist .label:nth-child(1) {
  margin-left: 0;
}

.bankcont_title_text {
  float: left;
  margin-right: 1rem;
  font-weight: bold;
}

.label_sonli {
  color: #5d87ff;
}

.cell {
  width: 500px;
}

.tag-item {
  margin-left: 5px;
}

.tagcontsize {
  color: #999;
}

.tagcontbigsize {
  margin-top: 0.5rem;
}

.cartcont {
  margin-top: 0.5rem;
}

.tableimg {
  width: 2rem;
  height: 2rem;
}
</style>
